package org.flexlancer.groups
{
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.containers.Canvas;
	import mx.controls.Label;
	import mx.core.UIComponent;
	
	import org.flexlancer.Logger.Logger;

	public class GroupItem extends Canvas
	{
		private var _linked_items:Array = new Array();
		private var prev_x:Number = 0;
		private var prev_y:Number = 0;
		public var group_label:Label = new Label();
		
		public function GroupItem()
		{
			try{
				super();
				this.setStyle("backgroundColor",0xFF22CC);
				this.setStyle("backgroundAlpha",0.2);
				
				this.addEventListener(MouseEvent.MOUSE_DOWN,Me_OnMouseDown);
				this.addEventListener(MouseEvent.MOUSE_UP,Me_OnMouseUp);
				this.group_label.setStyle("left",0);
				this.group_label.setStyle("top",0);
				this.addChild(this.group_label);
				this.group_label.setStyle("fontFamily","myFont");
				this.group_label.text = "Test test test test test";
			}catch(err:Error){
				Logger.LogE(err);
			}
		}
		
		public function get LinkedItem():Array { return this._linked_items; }
		
			
		private function Me_OnMouseDown(evt:MouseEvent):void{
			try{
				this.startDrag();
				this.prev_x = this.stage.mouseX;
				this.prev_y = this.stage.mouseY;
				evt.stopImmediatePropagation();
				this.addEventListener(MouseEvent.MOUSE_MOVE,Me_OnMouseMove);
			}catch(err:Error){
				Logger.LogE(err);
			}
		}

		private function Me_OnMouseUp(evt:MouseEvent):void{
			try{
				this.stopDrag();
				this.removeEventListener(MouseEvent.MOUSE_MOVE,Me_OnMouseMove);
			}catch(err:Error){
				Logger.LogE(err);
			}
		}
		public function Move(dx:Number,dy:Number):void{
			try{
				
				for each ( var btn:UIComponent in this._linked_items ) {
					btn.x += dx;
					btn.y += dy;
				}
				this.x += dx;
				this.y += dy;
				this.dispatchEvent(new Event("MoveGroup"));
			}catch(err:Error){
				Logger.LogE(err);
			}
		}
		private function Me_OnMouseMove(evt:MouseEvent):void{
			try{
				var mx:Number = this.stage.mouseX;
				var my:Number = this.stage.mouseY;
				
				for each ( var btn:UIComponent in this._linked_items ) {
//					if ( btn is Button ){
						btn.x += (mx - this.prev_x);
						btn.y += (my - this.prev_y);
//					}else if (btn is GroupItem ){
//						GroupItem(btn).Move(mx - this.prev_x,my - this.prev_y);
//					}
				}
				this.prev_x = mx;
				this.prev_y = my;
				this.dispatchEvent(new Event("MoveGroup"));
			}catch(err:Error){
				Logger.LogE(err);
			}
		}
	}
}